'use strict';
import koa from 'koa';
import moment from "moment"
import path from "path";
// import Request from "./api/request";
import schedule from "../tools/schedule";
var app = new koa();


app.keys = ['project zrcf-course-h5 secret', 'stronger the zrcf-course-h5'];

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'user-service' },
  transports: [
    //
    // - Write all logs with level `error` and below to `error.log`
    // - Write all logs with level `info` and below to `combined.log`
    //
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    // new winston.transports.File({ filename: 'combined.log' }),
  ],
});


var available_code_map = new Map(new Set([400, 401, 403, 404, 500]).entries());


app.use(async(ctx, next) => {
    try {
        await next();
    } catch (err) {
        if (!(err && err.statusCode)) {
            logger.error(`===============${moment().format("YYYY-MM-DD HH:mm:ss")}--报错信息===================\n${err}\n${JSON.stringify(ctx)}`);
        }
        console.log(err)
        var code = available_code_map.get(err
          ? err.statusCode
          : 500) || 500;
      
        ctx.response.status = code;
        await ctx.view(`error/${code}`, {code, url: ctx.request.url});
    }
});




require('./api/request').default(app);
app.use(require('koa-bodyparser')());

app.use(require('koa-logger')())

require('./middleware').default(app);
// require('./middleware/captcha').default(app);

const port = 20000;

// const server = require('http').createServer(app.callback());
// const io = require('socket.io')(server);
// const nsp = io.of("/duhuijie");


// nsp.on('connection', (socket) => {
  
//   app.context.duhuijie = () => {
//     // socket.emit("hello", "调用的");
//     console.log(io.sockets.connected , "--",nsp.sockets)
//     Object.keys(nsp.sockets).forEach((id) => {
//       nsp.sockets[id].emit('hello', "全")
//     })
//     // nsp.sockets.emit('hello', "全
//   }
//   socket.on("hello", (arg) => {
//     console.log("来自客户端：",arg); // world
//   });
//   socket.emit("hello", "初始化的");
// });

// require('./api').default(app);
require('./view').default(app);
require('./route').default(app);

process.on('uncaughtException', function(err) {
  logger.error(`===============${moment().format("YYYY-MM-DD HH:mm:ss")}--报错信息===================\n${err}`);
    
});


// server.listen(port);
app.listen(port);



console.log('listening on port ', port);

